const express = require('express');
const request = require('request').defaults({ encoding: null });

const app = express();

app.get('/convert-to-base64', (req, res) => { 
  const imageUrl = req.query.url;
  if (!imageUrl) {
    return res.status(400).send('Image URL is required');
  }

  request.get(imageUrl, (error, response, body) => {
    if (!error && response.statusCode === 200) {
      const base64 = `data:${response.headers['content-type']};base64,${Buffer.from(body).toString('base64')}`;
      res.send(base64);
    } else {
      res.status(500).send('Could not convert image to Base64');
    }
  });
});
app.get('/download-mp4', (req, res) => { 
  const videoUrl = req.query.url;
  
  if (!videoUrl) {
    return res.status(400).send('视频URL是必须的');
  }
  // 设置响应头
  const fileName = "downloaded.mp4"; // 这个可以根据实际内容动态设置
  res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);

  // 把请求结果导向客户端的响应
  request.get(videoUrl)
    .on('error', function(err) {
      console.error(err);
      res.status(500).send('下载视频时发生错误');
    })
    .pipe(res);
});

module.exports = {
  path: '/webapi',  
  handler: app
};